package com.ljsw.util;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.widget.Toast;

public class NonnNet extends Service{
	public static boolean netWork = true;
	private ConnectivityManager connectivityManager;
    private NetworkInfo info;
    private NetworkInfo wifi;
    private NetworkInfo modl;
    private int type=-1;
      
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		//注册广播
		 IntentFilter mFilter = new IntentFilter();
	     mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
	     registerReceiver(broadcastreceiver, mFilter);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		//解除广播
		unregisterReceiver(broadcastreceiver);
	}
	
	
	/**
	 * 网络每次发生变化，系统会发现一个ConnectivityManager.CONNECTIVITY_ACTION广播
	 * 通过这个广播监测网络状态，及网络类型
	 */
	
	private BroadcastReceiver broadcastreceiver = new BroadcastReceiver(){

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action.equals(ConnectivityManager.CONNECTIVITY_ACTION)){			
				connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				info = connectivityManager.getActiveNetworkInfo();		
				//有网络
				if(info!=null && info.isConnectedOrConnecting()){	
					netWork = true;										
					type = info.getType();
					if(info.getType()==connectivityManager.TYPE_MOBILE){						
						Toast.makeText(context,"你正在使用流量",Toast.LENGTH_SHORT).show();	
					}else if(info.getType()==connectivityManager.TYPE_WIFI){
						Toast.makeText(context,"wifi已连接",Toast.LENGTH_SHORT).show();	
					}						
				}else{	//无网络					
					netWork = false;					
					if (ConnectivityManager.TYPE_MOBILE == type) {
						Toast.makeText(context, "网络已断开", Toast.LENGTH_SHORT).show();
					} else if (ConnectivityManager.TYPE_WIFI == type) {
						Toast.makeText(context, "wifi网络已断开", Toast.LENGTH_SHORT).show();
					} else if (type == -1) {
						Toast.makeText(context, "网络未连接", Toast.LENGTH_SHORT).show();
					}
				}										
			}				
		}		
	}; 
}

